package com.atguigu.srb.core.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.srb.core.listener.ExcelDictDtoListener;
import com.atguigu.srb.core.mapper.DictMapper;
import com.atguigu.srb.core.pojo.dto.ExcelDictDto;
import com.atguigu.srb.core.pojo.entity.Dict;
import com.atguigu.srb.core.service.DictService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 数据字典 服务实现类
 * </p>
 *
 * @author lwm
 * @since 2022-02-10
 */
@Service
@Slf4j
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {
    @Resource
    private RedisTemplate redisTemplate;

    //数据批量读取导入操作
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void importData(InputStream inputStream) {
        EasyExcel.read(inputStream, ExcelDictDto.class, new ExcelDictDtoListener(baseMapper)).sheet().doRead();
    }

    //查询所有数据字典封装到集合
    @Override
    public List<ExcelDictDto> listDictData() {
        return baseMapper.selectDtoList();
    }

    //根据父id获取子节点数据列表
    @Override
    public List<Dict> listByParentId(Long parentId) {
        List<Dict> dictList = null;
        //先从redis中获取
        try {
            dictList = (List<Dict>) redisTemplate.opsForValue().get("dict:parentId:" + parentId);
            if (dictList != null && !dictList.isEmpty()) {
                log.info("成功从redis缓存拿到数据字典");
                return dictList;
            }
        } catch (Exception e) {
            log.error("redis数据字典缓存服务异常" + ExceptionUtils.getStackTrace(e));
        }
        //从mysql中查询所有数据
        List<Dict> all = baseMapper.selectList(null);
        //遍历组装数据
        dictList = new ArrayList<>();
        for (Dict dict : all) {
            if (parentId.longValue() == dict.getParentId()) {
                //设置是否有子集合的标记
                dict.setHasChildren(hasChildren(dict.getId(), all));
                //添加到集合中
                dictList.add(dict);
            }
        }

        try {
            //存储到redis
            if (!dictList.isEmpty()) {
                redisTemplate.opsForValue().set("dict:parentId:" + parentId, dictList, 7, TimeUnit.DAYS);
            }
        } catch (Exception e) {
            log.error("数据字典存入redis出现异常：" + ExceptionUtils.getStackTrace(e));
        }
        return dictList;
    }

    //根据dicCode获取子集合
    @Override
    public List<Dict> listByDictCode(String dictCode) {
        //根据dictCode找到对应dict
        LambdaQueryWrapper<Dict> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Dict::getDictCode, dictCode);
        Dict dict = baseMapper.selectOne(wrapper);
        List<Dict> dictList = null;
        if (dict != null) {
            //调用方法根据id查子集合列表
            dictList = listByParentId(dict.getId());
        }
        return dictList;
    }

    //根据value找到对应dict文本
    @Override
    public String getText(String dictCode, Integer value) {
        //先根据dictCode找到子集合
        List<Dict> dictList = listByDictCode(dictCode);
        String text = null;
        if (dictList != null && dictList.size() >0){
            for (Dict dict : dictList) {
                if (dict.getValue() == value.intValue()){
                    text = dict.getName();
                }
            }
        }
        return text;
    }

    //判断是否存在子集合 即是否id和parentId一样
    private Boolean hasChildren(Long id, List<Dict> all) {
        boolean hasChildren = false;
        for (Dict dict : all) {
            //存在子集合
            if (id.longValue() == dict.getParentId()) {
                hasChildren = true;
                break;
            }
        }
        return hasChildren;
    }


}
